package com.rankeiot.easy.vue.handler;

import com.inet.lib.less.Less;

import com.rankeiot.easy.vue.EasyVueConfiguration;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;


import java.io.InputStream;
import java.nio.charset.Charset;

public class LessHandler implements HandlerInterceptor {
    private ResourceLoader resourceLoader;
    public LessHandler(ResourceLoader resourceLoader){
        this.resourceLoader=resourceLoader;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        String newPath = path.substring(0, path.length() - 3) + "less";
        Resource resource= resourceLoader.getResource("classpath:/static"+newPath);
        if(resource.exists()){
            if(EasyVueConfiguration.devModel){
                response.setHeader("Cache-Control","no-store");
            }
            try(InputStream in= resource.getInputStream()){
                response.setContentType("text/css");
                String source = StreamUtils.copyToString(in, Charset.defaultCharset());
                response.getWriter().write(Less.compile(null, source, false));
                return false;
            }
        }
        return true;
    }
}
